<?php

namespace app\api\model;

use think\Db;

class CartModel extends Model
{
    public function getByUserId($user_id)
    {

        return Db::table('cart')->where(['user_id' => $user_id])->field('sku_id,sku_title,goods_price,goods_num,goods_title,id,goods_totalPrice,img')->select();
    }

    public function getById($id)
    {
        return Db::table('cart')->where(['id' => $id])->field('sku_id,sku_title,goods_price,goods_num,goods_title,id,goods_totalPrice')->select();
    }


    public function add($data)
    {
        return Db::table('cart')->insert($data);
    }

    public function addNum($goods_title, $goods_num, $user_id, $goods_skuId)
    {
        $num = Db::table('cart')->where(['user_id' => $user_id, 'goods_title' => $goods_title, 'sku_id' => $goods_skuId])->value('goods_num');
        $goods_price = Db::table('cart')->where(['user_id' => $user_id, 'goods_title' => $goods_title, 'sku_id' => $goods_skuId])->value('goods_price');
        $num = $num + $goods_num;
        $goods_totalPrice = $num * $goods_price;
        $data = [
            'goods_totalPrice' => $goods_totalPrice,
            'goods_num' => $num
        ];
        return Db::table('cart')->where(['user_id' => $user_id, 'goods_title' => $goods_title, 'sku_id' => $goods_skuId])->update($data);
    }

    public function delete($id)
    {
        return Db::table('cart')->where(['id' => $id])->delete();
    }

    public function isExistence($user_id, $goods_title, $goods_skuId)
    {
        return Db::table('cart')->where(['user_id' => $user_id, 'goods_title' => $goods_title, 'sku_id' => $goods_skuId])->find();
    }

    public function update($id, $goods_num)
    {
        $goods_price = Db::table('cart')->where(['id' => $id])->value('goods_price');
        $goods_totalPrice = $goods_num * $goods_price;
        $data = [
            'goods_totalPrice' => $goods_totalPrice,
            'goods_num' => $goods_num
        ];
        return Db::table('cart')->where(['id' => $id])->update($data);
    }

    public function getNameById($pro_no)
    {
        return Db::table('product')->where(['pro_no' => $pro_no])->value('title');
    }
    public function getImgById($pro_no)
    {
        return Db::table('product')->where(['pro_no' => $pro_no])->value('img');
    }

    public function getImgByTitle($pro_title)
    {
        return Db::table('product')->where(['title' => $pro_title])->value('img');
    }

    public function getSkuById($id)
    {
        return Db::table('product_sku')->where(['id' => $id])->field('sku_title,sku_price')->select();
    }

    public function getCount($user_id)
    {
        $list = Db::table('cart')->where(['user_id' => $user_id])->select();
        return count($list);
    }


}